package com.mairuide._frame.utils.sheethandler.oneKey;

import com.mairuide._frame.utils.ReflectUtils;
import com.mairuide._frame.utils.RegUtil;
import com.mairuide._frame.utils.SpringUtil;
import com.mairuide.bill.utils.DateUtils;
import com.mairuide.exceltitle_dict.enum2.FieldTypeEnum;
import com.mairuide.one_click_search.pojo.DataSource;
import com.mairuide.one_click_search.pojo.DataTemplate;
import com.mairuide.one_click_search.pojo.DataTemplateField;
import com.mairuide.one_click_search.service.DataTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-05-14 9:12
 * 处理03版的excel，因为sax不支持03的
 */
public class OneKeyExcel03SheetHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private  AtomicInteger count = new AtomicInteger(0);
    private Map<String,Object> resultMap = new HashMap<String,Object>();  //结果MAP
    private Map<String,Object> paraMap = new HashMap<String,Object>();  //参数MAP
    private DataSource dataSource;
    private Map<String, DataTemplateField> dataTemplateFieldMap = null;
    private  List<DataSource> data = new ArrayList<DataSource>();
    private DataTemplate dataTemplate;

    public  void deal(Workbook wb){
        Iterator<Sheet> sheetIterator = wb.sheetIterator();
        while(sheetIterator.hasNext()){
            Sheet sheet = sheetIterator.next();
            int numberOfRows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < numberOfRows; i++) {
                check();
                Row row = sheet.getRow(i);
                if (row==null) continue;
                int physicalNumberOfCells = row.getPhysicalNumberOfCells();
                DataSource dataSource = null;
                for (int j = 0; j < physicalNumberOfCells; j++) {
                    Cell cell = row.getCell(j);
                    if (cell==null) continue;
                    //cell.setCellType(Cell.CELL_TYPE_STRING);
                    DataFormatter formatter = new DataFormatter();
                    String val = formatter.formatCellValue(cell);
                    String cellValue = val;
                    Object object = null;
                    if (cellValue!=null){
                        cellValue= RegUtil.replaceBlank(cellValue);
                        object = cellValue;
                    }
                    if (StringUtils.isBlank(cellValue)) continue;
                    //System.out.println(cellValue);
                    if (dataTemplateFieldMap!=null&&i>dataTemplate.getBeginLine()){
                        dataSource = new DataSource();
                        DataTemplateField dataTemplateField = dataTemplateFieldMap.get(DataTemplateService.getColName(j+""));
                        if (dataTemplateField!=null){
                            //数据库字段
                            String classField = dataTemplateField.getColname();
                            try {
                                Class aClass = FieldTypeEnum.getFieldTypeEnumByVal(dataTemplateField.getSjlx());
                                if (aClass.equals(Timestamp.class) ){
                                    Date d= DateUtils.getDate(cellValue);
                                    if (d==null) continue;
                                    object = DateUtils.getDateString(d);
                                }else if (aClass.equals(BigDecimal.class) ){
                                    object=new BigDecimal(cellValue);
                                    object=String.valueOf(object);
                                }else if (aClass.equals(Integer.class) ){
                                    object=Integer.valueOf(cellValue);
                                    object=String.valueOf(object);
                                }
                                ReflectUtils.setValue(dataSource,DataSource.class,classField,String.class,object);
                            } catch (NumberFormatException e) {
                                logger.info("导入报错》》》值为："+object+",字段为："+classField+",第"+i+"行");
                                e.printStackTrace();
                            }
                        }
                    }
                }
                if (dataSource!=null){
                    data.add(dataSource);
                    int successNum = count.incrementAndGet();
                    resultMap.put("successNum",successNum);
                }
            }
        }
    }

    public void check(){
        if (data.size()>=10000){
            doSomething();
            data = new ArrayList<DataSource>();
        }
    }

    public void doSomething(){
        for (int i = 0; i < data.size(); i++) {
            DataSource dataSource = data.get(i);
            dataSource.setTablename(dataTemplate.getTablename());
            dataSource.setUuid(paraMap.get("uuid").toString());
            dataSource.setCreateId((Integer) paraMap.get("platManagerId"));
            dataSource.setCreateTime(new Timestamp(System.currentTimeMillis()));
            dataSource.setIsDelete(0);
        }
        DataTemplateService dataTemplateService = SpringUtil.getBean(DataTemplateService.class);
        dataTemplateService.batchSave(data);
    }

    public Map<String, Object> getResultMap() {
        return resultMap;
    }

    public void setResultMap(Map<String, Object> resultMap) {
        this.resultMap = resultMap;
    }

    public Map<String, Object> getParaMap() {
        return paraMap;
    }

    public void setParaMap(Map<String, Object> paraMap) {
        this.paraMap = paraMap;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Map<String, DataTemplateField> getDataTemplateFieldMap() {
        return dataTemplateFieldMap;
    }

    public void setDataTemplateFieldMap(Map<String, DataTemplateField> dataTemplateFieldMap) {
        this.dataTemplateFieldMap = dataTemplateFieldMap;
    }

    public List<DataSource> getData() {
        return data;
    }

    public void setData(List<DataSource> data) {
        this.data = data;
    }

    public DataTemplate getDataTemplate() {
        return dataTemplate;
    }

    public void setDataTemplate(DataTemplate dataTemplate) {
        this.dataTemplate = dataTemplate;
    }
}
